package org.diysearch.services;

import java.util.HashMap;
import java.util.Map;

import org.diysearch.helpers.PageHelper;
import org.diysearch.interfaces.Product;
import org.diysearch.models.Page;
import org.diysearch.products.HtmlProduct;

public class DisplayPage extends BaseService {
	private String template404;
	private String template503;
	
	@Override
	public Product execute() throws Exception {
		if (request.getParameter("do") == null) {
			return get503("uri (aka do) is a required parameter");
		}
		
		String  uri = request.getParameter("do");
		Page page = PageHelper.getPage(uri);
		
		if (page == null) {
			return get404(uri);
		}
		Product p = new HtmlProduct();
		Map<String,Object> content = new HashMap<String,Object>();
		content.put("page", page);
		p.setWriter(writer);
		p.setCompleted("template:"+page.getTemplate(),request,response,template,content);
		return p;
	}

	@Override
	public boolean isWriter() {
		return true;
	}
	
	private Product get503(String reason) throws Exception {
		Product p = new HtmlProduct();
		p.setWriter(writer);
		Map<String,Object> content = new HashMap<String,Object>();
		content.put("reason", reason);
		p.setWriter(writer);
		p.setCompleted("template:"+this.template503, request, response, template, content);
		return p;
	}
	
	private Product get404 (String uri) throws Exception {
		Product p = new HtmlProduct();
		Map<String,Object> content = new HashMap<String,Object>();
		content.put("uri", uri);
		p.setWriter(writer);
		p.setCompleted("template:"+this.template404, request, response, template, content);
		return p;
	}
	
	public void setTemplate503(String template) {
		this.template503 = template;
	}
	
	public void setTemplate404(String template) {
		this.template404 = template;
	}

	@Override
	public String getUri() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setUri(String uri) {
		// TODO Auto-generated method stub
		
	}

}
